﻿//-----------------------------------------------------------------------------
// Filename: MapSIPSwitchController.cs
//
// Description: Controller for the Google Map Mashup, showing MySIPSwitch registrations.
// 
// History:
// 6 Feb 2008	Guillaume Bonnet	    Created.
//
// License: 
// This software is licensed under the BSD License http://www.opensource.org/licenses/bsd-license.php
//
// Copyright (c) 2007 Aaron Clauson (aaronc@blueface.ie), Blueface Ltd, Dublin, Ireland (www.blueface.ie)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that 
// the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 
// Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following 
// disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of Blue Face Ltd. 
// nor the names of its contributors may be used to endorse or promote products derived from this software without specific 
// prior written permission. 
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, 
// BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, 
// OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
// OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
// POSSIBILITY OF SUCH DAMAGE.
//-----------------------------------------------------------------------------

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Web;
using System.Xml;
using log4net;
using MaverickLite.Security;
using BlueFace.Sys;
using BlueFace.VoIP.Net.SIP;
using GeoLocator;


namespace mapsipswitch
{
    public class MapSIPSwitchController : SecureXmlController
    {
        private static string m_adminEmail = AppState.GetConfigSetting("SIPSwitchAdminEmail");        
        private static ILog logger = AppState.logger;

        private static string m_MSSDBConnStr = AppState.GetConfigSetting("SIPSwitchDBConnStr");
        private static StorageTypes m_MSSDBStorageType = StorageTypes.Postgresql;
        private StorageLayer m_storagelayer;

        private string m_GeoDateBDPath = AppState.GetConfigSetting("MapSIPSwitchDBPath"); 
        private LookupService m_ls;

        public MapSIPSwitchController(XmlElement initParams): base(initParams)
        {
            m_storagelayer = new StorageLayer(m_MSSDBStorageType, m_MSSDBConnStr);
            m_ls = new LookupService(m_GeoDateBDPath, LookupService.GEOIP_STANDARD);
        }

        protected override void InitialiseRequest(HttpContext context)
        {
            base.InitialiseRequest(context);
        }

        public override void BuildPageModel()
        {
            try
            {
                logger.Debug("MapSIPSwitch : Loading details");
                string markers = "<markers>";                

                // Select all SIPURIs from DB
                DataSet setCount = m_storagelayer.GetDataSet("SELECT count(*) from sipaccountcontacts");
                DataSet set = m_storagelayer.GetDataSet("SELECT contacturi from sipaccountcontacts");

                int counter = 0;
                try
                {
                    counter = Int32.Parse(setCount.Tables[0].Rows[0][0].ToString());
                    logger.Debug("marker counter " + counter);
                }
                catch (Exception ex)
                {
                    logger.Error("MapSIPSwitchController Exception while trying to parse the counter : " + ex.Message);
                }

                for (int i = 0; i < counter; i++)
                {
                    markers += getMarkerFromSIPURI(set.Tables[0].Rows[i]["contacturi"].ToString());
                }
                
                markers += "<marker><lat>53.333</lat><lng>-6.249</lng></marker>";   // My SIP Switch server
                markers += "<marker><lat>44.4833</lat><lng>11.3333</lng></marker>"; // guillaume
                markers += "</markers>";
                m_pageModel.AddToModel("<page>" + markers + "</page>", true);
            }
            catch (Exception ex)
            {
                logger.Error("MapSIPSwitchController BuildPageModel Exception " + ex.Message);
                Email.SendEmail(m_adminEmail, "MapSIPSwitchController", "MapSIPSwitchController exception ", ex.Message);
            }
        }

        /// <summary>
        /// Retreives the IP from the SIPURI, and gets latitude and longitude parameters from the Maxmind DB
        /// </summary>
        /// <returns>string containing the marker</returns>
        string getMarkerFromSIPURI(string SIPURItoParse)
        {
            string marker = null;
            try
            {
                if (SIPURItoParse != null)
                {
                    string ip = SIPURI.ParseSIPURI(SIPURItoParse).GetURIEndPoint().Address.ToString();
                    if (ip != null)
                    {
                        Location l = m_ls.getLocation(ip);
                        if (l != null)
                        {
                            if (l.latitude != 0 && l.longitude != 0)
                            {
                                marker = "<marker><lat>" + l.latitude + "</lat><lng>" + l.longitude + "</lng></marker>";
                                logger.Debug("New marker : " + marker);
                            }
                        }
                        else
                        {
                            logger.Debug("could not geolocate from that IP : " + ip);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error("MapSIPSwitchController getMarkerFromSIPURI exception " + ex.Message);
            }
            return marker;
        }
    }
}
